package com.hundsun.yr.universal.library.base;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.TextView;

import com.hundsun.yr.universal.library.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.common.MD5Utils;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.utils.ThemeUtils;
import com.hundsun.yr.universal.library.view.BrowserLayout;

import org.apache.http.util.EncodingUtils;

import java.io.File;
import java.util.HashMap;


/**
 * @Title: BaseWebActivity.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @date 2015-10-22 下午4:08:18
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 * @version V1.0
 */
public abstract class BaseWebActivity extends BaseAppCompatActivity{

    public static final String BUNDLE_KEY_URL = "BUNDLE_KEY_URL";
    public static final String BUNDLE_KEY_HEADER = "BUNDLE_KEY_HEADER";
    public static final String BUNDLE_KEY_TITLE = "BUNDLE_KEY_TITLE";
    public static final String BUNDLE_KEY_SHOW_BOTTOM_BAR = "BUNDLE_KEY_SHOW_BOTTOM_BAR";
    public static final String BUNDLE_KEY_LOADTYPE = "BUNDLE_KEY_LOADTYPE";
    public static final String BUNDLE_KEY_PARAMS = "BUNDLE_KEY_PARAMS";

    protected String mWebUrl = null;
    protected HashMap mHeader = null;
    protected String mWebTitle = null;
    protected boolean isShowBottomBar = true;
    protected String postData = null;

    protected Toolbar mToolBar = null;
    protected BrowserLayout mBrowserLayout = null;
    protected BrowserLayout mBrowserLayout2 = null;
    protected LoadType mLoadType=LoadType.getDefaultType();
    /** 标题 **/
    protected TextView toolbar_title=null;
	/** 标题栏menu文字 **/
	protected TextView toolbar_menu=null;


	/**
	 * 加载方式枚举
	 */
    public static enum LoadType{
    	HTTP(0x0),//加载地址
		LOCAL(0x1),//本地数据
		DATA(0x2),//本地网页
		DATAWITHBASEURL(0x3),
        POSTDATA(0x4);

		public static LoadType load_http = LoadType.HTTP;
		public static LoadType getDefaultType() {
			return load_http;
		}

		public static LoadType mapIntToValue(final int modeInt) {
			for (LoadType value : LoadType.values()) {
				if (modeInt == value.getIntValue()) {
					return value;
				}
			}

			// 没有则返回默认的
			return getDefaultType();
		}

		private int mIntValue;

		LoadType(int modeInt) {
			mIntValue = modeInt;
		}

		public int getIntValue() {
			return mIntValue;
		}
    }



    @Override
    protected void getBundleExtras(Bundle extras) {
        mWebTitle = extras.getString(BUNDLE_KEY_TITLE);
        mWebUrl = extras.getString(BUNDLE_KEY_URL);
        if (extras.getSerializable(BUNDLE_KEY_HEADER) != null){
            mHeader = ((HeaderMap)extras.getSerializable(BUNDLE_KEY_HEADER)).getMap();
        }

        isShowBottomBar = extras.getBoolean(BUNDLE_KEY_SHOW_BOTTOM_BAR);
        mLoadType=LoadType.mapIntToValue(extras.getInt(BUNDLE_KEY_LOADTYPE, 0));

        if (extras.getSerializable(BUNDLE_KEY_PARAMS) != null){
            postData = extras.getString(BUNDLE_KEY_PARAMS);
        }
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_common_web;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {

    }
    @SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (isApplyKitKatTranslucency()) {
			setSystemBarTintDrawable(getResources().getDrawable(ThemeUtils.getStatusbar_color()));
		}
	}

	@Override
	protected int configTheme() {
		// TODO Auto-generated method stub
		// int theme = ThemeUtils.themeArr[ThemeUtils.getThemeColorIndex()][0];
		int theme = ThemeUtils.getTheme();
		if (theme > 0)
			return theme;
		return super.configTheme();
	}

    @Override
    protected View getLoadingTargetView() {
        return mBrowserLayout;
    }

	@SuppressWarnings("deprecation")
	@Override
    protected void initViewsAndEvents() {
		setSystemBarTintDrawable(getResources().getDrawable(ThemeUtils.getStatusbar_color()));

        mToolBar = (Toolbar) findViewById(R.id.common_toolbar);
        mBrowserLayout = (BrowserLayout) findViewById(R.id.common_web_browser_layout);
        mBrowserLayout2 = (BrowserLayout) findViewById(R.id.common_web_browser_layout2);

        if (null != mToolBar) {
            setSupportActionBar(mToolBar);
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("");
            toolbar_title = findView(R.id.toolbar_title);
			toolbar_menu = findView(R.id.toolbar_menu);
        }

        if (!TextUtils.isEmpty(mWebTitle)) {
            setTitle(mWebTitle);
        } else {
            setTitle("网页");
        }

        if (!TextUtils.isEmpty(mWebUrl)) {
        	if(mLoadType==LoadType.HTTP||mLoadType==LoadType.LOCAL){
                if (mHeader != null){
                    mBrowserLayout.loadUrl(mWebUrl,mHeader);
                } else {
                    mBrowserLayout.loadUrl(mWebUrl);
                }
        	}else if(mLoadType==LoadType.DATA){
//                if (mHeader != null){
//                    mBrowserLayout.loadUrl(mWebUrl,mHeader);
//                } else {
//                    mBrowserLayout.loadUrl(mWebUrl);
//                }
        		mBrowserLayout.loadData(mWebUrl);
        	}else if(mLoadType==LoadType.DATAWITHBASEURL){
        		mBrowserLayout.loadDataWithBaseURL(mWebUrl);
        	} else if (mLoadType == LoadType.POSTDATA){
                mBrowserLayout.mWebView.postUrl(mWebUrl, EncodingUtils.getBytes(postData, "BASE64"));
            }
        } else {
            showToast("获取URL地址失败");
        }

        if (!isShowBottomBar) {
            mBrowserLayout.hideBrowserController();
            mBrowserLayout.setVerticalScrollBarEnabled(false);
            mBrowserLayout.setHorizontalScrollBarEnabled(false);
        } else {
            mBrowserLayout.showBrowserController();
        }
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

	/**
	 * 设置标题
	 *
	 * @param res
	 */
	public void setToolbarTitle(int res) {
		if (null != toolbar_title) {
			toolbar_title.setText(res);
		}
	}

	/**
	 * 设置标题
	 *
	 * @param titlle
	 */
	public void setToolbarTitle(String titlle) {
		if (null != toolbar_title) {
			toolbar_title.setText(titlle);
		}
	}

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return true;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return TransitionMode.RIGHT;
    }

    /**
	 * 是否改变状态栏背景
	 *
	 * @return
	 */
	protected abstract boolean isApplyKitKatTranslucency();

    @Override
    protected void onDestroy() {
        if (mBrowserLayout.mWebView != null){
            ViewGroup parent = (ViewGroup) mBrowserLayout.mWebView.getParent();
            if (parent != null){
                parent.removeView(mBrowserLayout.mWebView);
            }

         /*   //清空所有Cookie
            CookieSyncManager.createInstance(getApplicationContext());  //Create a singleton CookieSyncManager within a context
            CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
            cookieManager.removeAllCookie();// Removes all cookies.
            CookieSyncManager.getInstance().sync(); // forces sync manager to sync now

            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");*/
            mBrowserLayout.mWebView.setWebChromeClient(null);
            mBrowserLayout.mWebView.setWebViewClient(null);
            mBrowserLayout.mWebView.getSettings().setJavaScriptEnabled(true);
            mBrowserLayout.mWebView.clearCache(true);
            mBrowserLayout.mWebView.removeAllViews();
            mBrowserLayout.mWebView.destroy();
        }
        super.onDestroy();
    }

    protected void syncCookie(Context context, String url,String user_no,String token){
        try{

            CookieSyncManager.createInstance(context);

            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            String oldCookie = cookieManager.getCookie(url);
            if(oldCookie != null){

            }
            cookieManager.setCookie(url, "user_no=" + user_no);
            cookieManager.setCookie(url, "token=" + token);
            cookieManager.setCookie(url, "key=" + MD5Utils.getMD5String(user_no + "happy2018"));
            cookieManager.setCookie(url, "accessFrom=Android");
            CookieSyncManager.getInstance().sync();

            String newCookie = cookieManager.getCookie(url);
            if(newCookie != null){

            }
        }catch(Exception e){

        }
    }

    protected void syncCookie(Context context, String url,String user_no,String token,String version){
        try{

            CookieSyncManager.createInstance(context);

            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            String oldCookie = cookieManager.getCookie(url);
            if(oldCookie != null){

            }
            cookieManager.setCookie(url, "user_no=" + user_no);
            cookieManager.setCookie(url, "token=" + token);
            cookieManager.setCookie(url, "key=" + MD5Utils.getMD5String(user_no + "happy2018"));
            cookieManager.setCookie(url, "accessFrom=Android");
            cookieManager.setCookie(url, "version=" + version);
            CookieSyncManager.getInstance().sync();

            String newCookie = cookieManager.getCookie(url);
            if(newCookie != null){

            }
        }catch(Exception e){

        }
    }

    protected void syncCookie(Context context, String url){
        try{

            CookieSyncManager.createInstance(context);

            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            String oldCookie = cookieManager.getCookie(url);
            if(oldCookie != null){

            }
            cookieManager.setCookie(url, "accessFrom=Android");
            CookieSyncManager.getInstance().sync();

            String newCookie = cookieManager.getCookie(url);
            if(newCookie != null){

            }
        }catch(Exception e){

        }
    }

    public void refresh(){
        if (mHeader != null){
            mBrowserLayout.loadUrl(mWebUrl,mHeader);
        } else {
            mBrowserLayout.loadUrl(mWebUrl);
        }
    }

}
